package process;

import device.*;
import javafx.application.Platform;
import memory.PCB;
import memory.PCBData;

public class DeviceInstruction extends Myinstuction {

	private char type;
	private int time;
	private int pid;
	
	public  DeviceInstruction(char type,int pid,int time) {
		this.time = time;
		this.type = type;
		this.pid = pid;
	}
	
	@Override
	public void run() {
		// TODO 未完成
		if(DeviceManage.callingDevice(type, CPU.getCpu().getPcb().getPid(), time))//尝试申请
		{	
//			System.out.println("调用设备 "+type+" 成功，进程id："
//					+pid+" 调用时间："+time);
			ProcessController.getProcessController().outPut("调用设备 "+type+" 成功，进程id："
					+CPU.getCpu().getPcb().getPid()+" 调用时间："+time+"\n");
			//申请成功保存PCB，进入阻塞队列，保存pc+1
			PCB pcb=CPU.getCpu().getPcb();
			pcb.setAx(CPU.getCpu().getAx());
			pcb.setPc(CPU.getCpu().getPc()+1);
			CPU.getCpu().getPcb().setType(type);
			PCBData.blockQueue.add(CPU.getCpu().getPcb());
			if(CPU.getCpu().choosePcb()) {
				CPU.getCpu().readPcb();
			}
			}
		else {//申请失败 ,保存PCB，进入阻塞队列，保存pc
			CPU.getCpu().setPsw_io(3);
			PCB pcb=CPU.getCpu().getPcb();
			pcb.setAx(CPU.getCpu().getAx());
			pcb.setPc(CPU.getCpu().getPc());
			CPU.getCpu().getPcb().setType(type);
			PCBData.blockQueue.add(CPU.getCpu().getPcb());
			if(CPU.getCpu().choosePcb()) {
				CPU.getCpu().readPcb();
			}
//			System.out.println("调用失败");
			Platform.runLater(() -> {
				ProcessController.getProcessController().outPut("调用失败\n");
			});
		}
	}

}
